using MediatR;
using Microsoft.AspNetCore.Mvc;
using WMS.Domain;
using WMS.ErrorCode;
using WMS.Infrasturcture.Interfaces;
using WMS.WebApiRead.Application.Command;
using WMS.WebApiRead.DTO;

namespace WMS.WebApiRead.Controllers
{
    /// <summary>
    /// 仓库信息读操作控制器（查询）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WarehouseController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<WarehouseController> logger;
        private readonly IBaseRepository<WarehouseInfo> warehouseRepository;
        private readonly IBaseRepository<WarehouseSupervisor> supervisorRepository;
        private readonly IBaseRepository<WarehouseDept> deptRepository;

        /// <summary>
        /// 构造函数，注入MediatR、日志服务和仓储
        /// </summary>
        public WarehouseController(
            IMediator mediator,
            ILogger<WarehouseController> logger,
            IBaseRepository<WarehouseInfo> warehouseRepository,
            IBaseRepository<WarehouseSupervisor> supervisorRepository,
            IBaseRepository<WarehouseDept> deptRepository)
        {
            this.mediator = mediator;
            this.logger = logger;
            this.warehouseRepository = warehouseRepository;
            this.supervisorRepository = supervisorRepository;
            this.deptRepository = deptRepository;
        }

        /// <summary>
        /// 分页查询仓库信息（支持条件筛选、联表查询）
        /// </summary>
        /// <param name="queryDTO">查询参数</param>
        /// <returns>返回分页结果</returns>
        [HttpGet]
        public async Task<ApiResult<ApiPaging<List<WarehouseInfoResultDTO>>>> QueryWarehouse([FromQuery] WarehouseQueryDTO queryDTO)
        {
            logger.LogInformation($"开始查询仓库信息，页码：{queryDTO.PageIndex}，每页大小：{queryDTO.PageSize}");

            return await mediator.Send(new WarehouseQueryCommand
            {
                QueryDTO = queryDTO
            });
        }

        /// <summary>
        /// 根据仓库ID查询仓库详情（联表查询）
        /// </summary>
        /// <param name="warehouseID">仓库ID</param>
        /// <returns>返回仓库详情</returns>
        [HttpGet]
        public async Task<ApiResult<WarehouseInfoResultDTO>> GetWarehouseById([FromQuery] int warehouseID)
        {
            logger.LogInformation($"开始查询仓库详情，仓库ID：{warehouseID}");

            try
            {
                // 联表查询：仓库信息 LEFT JOIN 主管表 LEFT JOIN 部门表
                var warehouseInfo = (from warehouse in warehouseRepository.GetAll()
                                     where warehouse.WarehouseID == warehouseID && !warehouse.IsDeleted
                                     join supervisor in supervisorRepository.GetAll()
                                     on warehouse.SupervisorId equals supervisor.SupervisorId into supervisorGroup
                                     from supervisor in supervisorGroup.DefaultIfEmpty()
                                     join dept in deptRepository.GetAll()
                                     on warehouse.WarehouseDeptId equals dept.WarehouseDeptId into deptGroup
                                     from dept in deptGroup.DefaultIfEmpty()
                                     select new WarehouseInfoResultDTO
                                     {
                                         WarehouseID = warehouse.WarehouseID,
                                         WarehouseCode = warehouse.WarehouseCode,
                                         WarehouseName = warehouse.WarehouseName,
                                         Warehousecapacity = warehouse.Warehousecapacity,
                                         SupervisorId = warehouse.SupervisorId,
                                         SupervisorName = supervisor != null ? supervisor.SupervisorName : "未分配",
                                         WarehouseDeptId = warehouse.WarehouseDeptId,
                                         WarehouseDeptName = dept != null ? dept.WarehouseDeptName : "未分配",
                                         WarehousePhone = warehouse.WarehousePhone,
                                         WarehouseAddress = warehouse.WarehouseAddress,
                                         WarehouseState = warehouse.WarehouseState,
                                         WarehouseLockdown = warehouse.WarehouseLockdown,
                                         WarehouseContent = warehouse.WarehouseContent,
                                         IsDeleted = warehouse.IsDeleted,
                                         DataStatus = warehouse.DataStatus,
                                         CreateName = warehouse.CreateName,
                                         CreateTime = warehouse.CreateTime,
                                         UpdateName = warehouse.UpdateName,
                                         UpdateTime = warehouse.UpdateTime,
                                         DeleteName = warehouse.DeleteName,
                                         DeleteTime = warehouse.DeleteTime
                                     }).FirstOrDefault();

                if (warehouseInfo == null)
                {
                    return new ApiResult<WarehouseInfoResultDTO>
                    {
                        Code = ApiResultEnum.查询失败,
                        Message = "仓库信息不存在",
                        Data = null
                    };
                }

                return new ApiResult<WarehouseInfoResultDTO>
                {
                    Code = ApiResultEnum.查询成功,
                    Message = "查询仓库详情成功",
                    Data = warehouseInfo
                };
            }
            catch (Exception ex)
            {
                logger.LogError($"查询仓库详情异常：{ex.Message}");
                return new ApiResult<WarehouseInfoResultDTO>
                {
                    Code = ApiResultEnum.查询失败,
                    Message = $"查询仓库详情异常：{ex.Message}",
                    Data = null
                };
            }
        }
    }
}

